<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DataViewInstance, fmtDate, hBtns, hStatusTag, openDialog, request, statusSelect, TableColumnProps } from '../../../utils';
import { Plus } from '@element-plus/icons-vue';
import router from '../../../router';

const columns = [
  { label: '字典名称', prop: 'dictName' },
  {
    label: '字典类型',
    minWidth: 170,
    render: (_, { row }) => {
      return hBtns({ label: row.dictType, onClick: goDetails.bind(null, row) })
    }
  },
  {
    label: '状态',
    render: (_, { row }) => hStatusTag(row.status)
  },
  { label: '备注', prop: 'remark' },
  {
    label: '创建时间',
    minWidth: 170,
    render: (h, { row }) => h('span', fmtDate(row.createAt))
  },
  {
    label: '操作',
    width: 120,
    fixed: 'right',
    render: (_, { row }) => {
      return hBtns([
        { label: '修改', onClick: onEdit.bind(null, row) },
        { label: '删除', type: 'danger', onClick: onDelete.bind(null, row) }
      ])
    }
  }
] as TableColumnProps<any>[]

const tableRef = ref<DataViewInstance>()

const fetchAction = (params: any) => {
  const { timerange, ...other } = params
  const [createBeginTime, createEndTime] = timerange ?? []
  return request('/dict/listByPage', {
    params: { ...other, createBeginTime, createEndTime }
  })
}

const onEdit = (row?: any) => {
  openDialog({
    vm: () => import('./edit.vue'),
    vmProps: { row },
    dialogProps: {
      title: row ? '编辑' : '新增',
      onSubmitted: () => tableRef.value?.getData()
    }
  })
}

const onDelete = (row: any) => {
  tableRef.value?.deleteRows({
    desc: '删除字典，该字典下的数据将被清空，确定继续？',
    action: () => request.post('/dict/delete', { id: row._id })
  })
}

const goDetails = (row: any) => {
  router.push(`dict/${row._id}`)
}

onMounted(() => {
  tableRef.value?.getData()
})
</script>

<template>
  <UiDataView ref="tableRef" :columns="columns" :fetch-action="fetchAction">
    <template #form="{ form, onSearch }">
      <ElFormItem label="字典名称">
        <ElInput placeholder="请输入字典名称" v-model="form.dictName" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="字典类型">
        <ElInput placeholder="请输入字典类型" v-model="form.dictType" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSelect placeholder="请选择状态" clearable v-model="form.status" @change="onSearch">
          <ElOption v-for="_ in statusSelect" :key="_.value" v-bind="_" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem style="width: 320px;" label="创建时间">
        <ElDatePicker
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          v-model="form.timerange"
          @change="onSearch" />
      </ElFormItem>
    </template>
    <template #actions>
      <ElButton plain type="primary" :icon="Plus" @click="onEdit()">新增</ElButton>
    </template>
  </UiDataView>
</template>
